<?php

namespace app\index\controller;

use app\common\controller\Balance;
use app\common\controller\CardPut;
use app\common\model\CardConsume;
use app\common\model\CardCzLog;
use app\common\model\CardFans;
use app\common\model\CardFollowcardlog;
use app\common\model\CardFreecard;
use app\common\model\CardFreecardlog;
use app\common\model\CardGift;
use app\common\model\CardGiftPayOrder;
use app\common\model\CardGivecardLog;
use app\common\model\CardLeaduser;
use app\common\model\CardMember;
use app\common\model\CardOrder;
use app\common\model\CardShareLog;
use app\common\model\CardShareRule;
use app\common\model\CardShareUser;
use app\common\model\CardUserGet;
use app\common\model\CardGeneral;
use app\common\model\CardPutRule;
use app\common\model\CardUserGetGift;
use app\common\model\CardUserUpdate;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\WxOpen;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\merchant\controller\Qrcodes;
use app\common\model\System;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Wxcardgift extends Controller
{


    //支付订单处理
    public function giftcardpay($param){
        try {
            $isgetoder = $this->getgiftcardpay($param);
            if ($isgetoder['errcode'] == 0){
                $CardGiftPayOrder = new CardGiftPayOrder();
                $event_statu = $CardGiftPayOrder->where(['orderid'=>$isgetoder['order']['order_id']])->value('event_statu');
                if ($event_statu == 0){
                    $Momchant = new Momerchant();
                    $wxOpen = new WxOpen();
                    $wx_open_id = $wxOpen->where(['gh_id'=>$param['gh_id']])->value('id');
                    //END
                    $data['top_mid'] = $Momchant->where(['wx_open_id'=>$wx_open_id])->value('id');
                    $data['gh_id'] = $param['gh_id'];
                    $data['orderid'] = $isgetoder['order']['order_id'];
                    $data['orderid'] = $isgetoder['order']['order_id'];
                    $data['page_id'] = $isgetoder['order']['page_id'];
                    $data['trans_id'] = $isgetoder['order']['trans_id'];
                    $data['add_time'] = $isgetoder['order']['create_time'];
                    $data['pay_time'] = $isgetoder['order']['pay_finish_time'];
                    $data['total_price'] = $isgetoder['order']['total_price'] / 100;
                    $data['openid'] = $isgetoder['order']['open_id'];
                    if (isset($isgetoder['order']['accepter_openid'])){$data['accepter_openid'] = $isgetoder['order']['accepter_openid'];}else{$data['accepter_openid'] = '';}
                    $data['outer_str'] = $isgetoder['order']['outer_str'];
                    $data['is_chatroom'] = $isgetoder['order']['is_chatroom'];
                    $data['nickname'] = $isgetoder['order']['nickname'];
                    $data['event_statu'] = 1;
                    $data['create_time'] = time();
                    $data['info'] = json_encode($isgetoder,JSON_UNESCAPED_UNICODE);
                    $data['card_list'] = json_encode($isgetoder['order']['card_list'],JSON_UNESCAPED_UNICODE);
                    $CardGiftPayOrder->allowField(true)->validate(['orderid'  => 'require|unique:CardGiftPayOrder'])->save($data);
                }else{
                    $su = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    echo $su;
                }
            }
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }
    }

    //查询订单详情
    public function getgiftcardpay($param){
        $url = 'https://api.weixin.qq.com/card/giftcard/order/get?access_token=';
        $data['order_id'] = $param['orderid'];
        $AccessToken = $this->getaccesstoken($param['gh_id']);
        $res = $this->http_post($url . $AccessToken, json_encode($data, JSON_UNESCAPED_UNICODE));
        //END
        $res = json_decode($res, true);
        return $res;
    }

    //获取accesstoken
    public function getaccesstoken($gh_id){
        $wxOpen = new WxOpen();
        $map['gh_id'] = $gh_id;
        $access = $wxOpen->where($map)->value('at_access_token');
        return $access;
    }

    private function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {
            if ($is_curlFile) {
                foreach ($param as $key => $val) {
                    if (substr($val, 0, 1) == '@') {
                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));
                    }
                }
            }
            $strPOST = $param;

        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);

        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


    //

    //领取
    public function usergetcard($datas)
    {

    }


    //微信API参数
    public function options($gh_id)
    {
        Session::set('openid', null);
        $Momerchant = new Momerchant();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mab['gh_id'] = $gh_id;
//        $config =$System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $agent = $Momerchant->where(['wx_open_id'=>$users['id']])->value('agent');
        $config = $Agent->where(array('id' => $agent))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }


}